import request from '@/server/request';
import { setLocal } from '@/utils/utils';
import { getAppId, setAppId } from '@/utils/local';

import { getUserAvatar } from '@/pages/TaskDetail/common';

export function commonRequest(data, url, method = 'post') {
  const requestData = {
    url,
    method
  };

  if (method === 'post') {
    requestData.data = data;
  } else {
    requestData.param = data;
  }

  return request(requestData);
}

export function pcLogin() {
  return request({
    url: '/mLogin/login',
    method: 'post',
    data: {
      // username: '13758127433',
      // username: '13868529891',
      // username: '13065738845',
      // username: '15728002892', // 胡
      // username: '18072266573', // 杰
      username: '13758127433', // 梁
      password: '123456',
      year: 2021,
      appId: getAppId()
    }
  });
}

export const dealLogin = (res) => {
  const { data, token } = res;
  const {
    roleIdList,
    enterprise,
    avatar,
    avatarId,
    telephone,
    trueName: userName,
    id: userId
  } = data;

  if (roleIdList && Array.isArray(roleIdList)) {
    roleIdList.forEach(sys => {
      sys.value = sys.id;
      sys.label = sys.name;

      const sC = sys.children;
      if (sC && Array.isArray(sC)) {
        sC.forEach(sr => {
          sr.value = sr.name;
          sr.label = sr.name;
        });
      }
    });
  }

  if (Array.isArray(enterprise)) {
    enterprise.forEach(item => {
      if (item) {
        item.label = item.name;
        item.value = item.isbnCode;
      }
    });
  }
  if (avatar && avatarId) {
    getUserAvatar({
      avatar: avatarId,
      avatarId: avatar,
      userId
    }, true).then(img => {
      if (img) {
        const eImg = new Event('userAvatar');
        eImg.value = img;
        dispatchEvent(eImg);
        setLocal({
          userAvatar: img
        });
      }
    });
  }
  setAppId(roleIdList[0].children[0].appId);

  setLocal([
    { token },
    { userName },
    { userTelephone: telephone },
    { userId },
    { roleList: roleIdList[0].children },
    { appRole: roleIdList[0].children[0].name },
    { appRoleId: roleIdList[0].children[0].id },
    { appUserQx: roleIdList },
    { mEnterprise: enterprise },
    { mIsbnCode: enterprise[0].value },
    { mEnterpriseId: enterprise[0].id },
    { mIsbnCodeName: enterprise[0].label }
  ]);
};

export function loginLocal() {
  return pcLogin().then(res => {
    if (res.success) {
      dealLogin(res);
    }
    return Promise.resolve(res);
  });
}
